const express = require('express');
const http = require('http');
const https = require('https');
const fs = require('fs');
const cors = require('cors');
const app = express();

// 中间件
app.use(cors());
app.use(express.json({ limit: '10mb' }));

// 存储已启动的Server实例（tabId -> { server: 服务实例, port: 端口 }）
const activeServers = {};

// 1. 启动Server接口（接收前端配置）
app.post('/api/server/start', (req, res) => {
    const { tabId, protocol, port, sslKey, sslCert, path, statusCode, headers, body } = req.body;

    // 检查端口是否已占用
    if (Object.values(activeServers).some(s => s.port === port)) {
        return res.json({ success: false, message: '端口已被占用' });
    }

    // 创建临时证书文件（HTTPS需要）
    let sslOptions = null;
    if (protocol === 'https') {
        try {
            // 将Base64证书转为文件
            fs.writeFileSync(`./temp-${tabId}-key.key`, Buffer.from(sslKey, 'base64'));
            fs.writeFileSync(`./temp-${tabId}-cert.crt`, Buffer.from(sslCert, 'base64'));
            sslOptions = {
                key: fs.readFileSync(`./temp-${tabId}-key.key`),
                cert: fs.readFileSync(`./temp-${tabId}-cert.crt`)
            };
        } catch (e) {
            return res.json({ success: false, message: 'SSL证书处理失败：' + e.message });
        }
    }

    // 创建Server
    const server = protocol === 'http' 
        ? http.createServer(app) 
        : https.createServer(sslOptions, app);

    // 监听指定端口
    server.listen(port, (err) => {
        if (err) {
            // 清理临时证书
            if (protocol === 'https') cleanTempFiles(tabId);
            return res.json({ success: false, message: '监听端口失败：' + err.message });
        }

        // 存储Server实例
        activeServers[tabId] = {
            server,
            port,
            protocol,
            path,
            statusCode,
            headers,
            body,
            serverId: `server-${Date.now()}-${tabId}` // 生成唯一ID
        };

        // 注册响应路由（仅对当前Server生效）
        app.get(path, (req, res) => {
            const serverConfig = activeServers[tabId];
            if (!serverConfig) return res.sendStatus(404);

            // 设置响应头
            Object.entries(serverConfig.headers).forEach(([key, value]) => {
                res.setHeader(key, value);
            });

            // 设置响应状态码和体
            res.status(serverConfig.statusCode).send(serverConfig.body);
        });

        res.json({ 
            success: true, 
            serverId: activeServers[tabId].serverId,
            message: `成功启动${protocol}服务（端口：${port}）`
        });
    });
});

// 2. 停止Server接口
app.post('/api/server/stop', (req, res) => {
    const { tabId } = req.body;
    const serverInfo = activeServers[tabId];

    if (!serverInfo) {
        return res.json({ success: false, message: '服务未启动' });
    }

    // 关闭Server
    serverInfo.server.close((err) => {
        if (err) {
            return res.json({ success: false, message: '停止服务失败：' + err.message });
        }

        // 清理临时证书和路由
        if (serverInfo.protocol === 'https') cleanTempFiles(tabId);
        delete activeServers[tabId];

        res.json({ success: true, message: '服务已停止' });
    });
});

// 辅助函数：清理临时证书文件
function cleanTempFiles(tabId) {
    try {
        if (fs.existsSync(`./temp-${tabId}-key.key`)) {
            fs.unlinkSync(`./temp-${tabId}-key.key`);
        }
        if (fs.existsSync(`./temp-${tabId}-cert.crt`)) {
            fs.unlinkSync(`./temp-${tabId}-cert.crt`);
        }
    } catch (e) {
        console.error('清理临时文件失败：', e);
    }
}

// 后端服务启动端口（与前端配置的Server端口无关）
const backendPort = 3000;
app.listen(backendPort, () => {
    console.log(`后端服务已启动：http://localhost:${backendPort}`);
});